package dd.server;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import dd.model.Event;
import dd.model.serverModel;

import server.ClientState;
import server.IProtocolHandler;
import xml.Message;

public class createResponseController implements IProtocolHandler {
	public Message process(ClientState client, Message request) {
		//save these information to serverModel
		//first create a serverModel
		serverModel sm = serverModel.getInstance();
		Event e = new Event();
		sm.setEvent(e);
		//get the request information
		Node update = request.contents.getFirstChild();
		NamedNodeMap map = update.getAttributes();
		//save data
		String thismode = map.getNamedItem("type").getNodeValue();
		System.out.println("mode: " + thismode);
		e.setMode(thismode);
		String thistype = map.getNamedItem("behavior").getNodeValue();
		System.out.println("type: " + thistype);
		e.setType(thistype);
		String thisname = map.getNamedItem("question").getNodeValue();
		System.out.println("name: "+ thisname);
		e.setEventName(thisname);
		String thisnumoflines = map.getNamedItem("numChoices").getNodeValue();
		int thisnumofline = Integer.parseInt(thisnumoflines);
		System.out.println("number of choices: "+thisnumoflines);
		e.setNumberLines(thisnumofline);
		String thisnumofedges = map.getNamedItem("numRounds").getNodeValue();
		int thisnumofedge = Integer.parseInt(thisnumofedges);
		System.out.println("number of Round: " + thisnumofedges);
		e.setNumberEdges(thisnumofedge);
		e.setEventID("135");
		System.out.println("event id set as: 135");
		//if this is closed mode, get the choice,and then get the username and password
	if(thismode.equals("closed")){
		//go to first child get choice
		update = update.getFirstChild();
		map = update.getAttributes();
		String choice = null;
	//	int index = 0;
		int i;
		//get the choice information
		choice = map.getNamedItem("value").getNodeValue();
		System.out.println("choice0 is:"+ choice);
		e.setChoice(0, choice);
		for(i=1;i<thisnumofline;i++){
			update = update.getNextSibling();
			map = update.getAttributes();
			choice = map.getNamedItem("value").getNodeValue();
			System.out.println("choice"+i+" is:"+ choice);
			e.setChoice(i, choice);
		}
	}
	//open mode get user name directly
	else
	{
		
	}
		// Construct message reflecting state
		String xmlString = Message.responseHeader(request.id()) +
				 "<createResponse id='"+e.getEventID()+"'>"+"</createResponse></response>";
		//record this id to server id for event 135
		sm.setuserid(0, request.id());
		sm.setnumofuserin(1);
		// send this response back to the client which sent us the request.
		return new Message (xmlString);
	}
}
